//mongoose操作数据库入口文件

const mongoose = require('mongoose')
const { uri, options } = require('./mongodb.config')
const { Static_Data, Document, top_view, YiriDoc, WeChat_Document } = require('./schema')
//创建连接
mongoose.connect(uri, options)
    .then(() => {
        console.log('连接成功')
    }).catch(err => {
        console.log(err)
        console.log('连接失败')
    })

//设置查询静态数据方法
function getStaticData(query) {
    return new Promise((reslove, reject) => {
        Static_Data.find(query, { _id: 0 }).then(res => reslove(res)).catch(err => reject(err))
    })
}

//一日文章
async function writeYiriDoc(data) {
    return new Promise(async (reslove, reject) => {
        YiriDoc.create(data, (err, res) => {
            if (err) {
                reject({ errMsg: err })
            }
            else {
                console.log('添加成功!')
                reslove({ errMsg: 'ok' })
            }
        })
    })
}

//保存微信公众号文章文章
async function writeWeChatDoc(data) {
    return new Promise(async (reslove, reject) => {
        WeChat_Document.findOne({ name: data.name }, async (err, res) => {
            if (err) {
                reject({ errMsg: err })
            }
            else {

                if (res) {
                    console.log('查询到有同名文档')
                    console.log(res)
                    reslove(res)
                } else {
                    console.log('未查询到有同名文档')
                    const num = await WeChat_Document.find({}).count() +1
              
                    data.id = 'WX-'+ num.toString().padStart(3,'0')
                    data.to = '/news/'+data.id
                    WeChat_Document.create({ ...data }, (err, res) => {
                        if (err) {
                            reject({ errMsg: err })
                        }
                        else {
                            console.log('添加成功!')
                            reslove(data)
                        }
                    })
                }
            }
        })
    })
}

//获得主题首页的方法
async function getTopicHome(id) {
    let topic = ''
    if (id === 'sleep') {
        topic = '睡眠'
    } else if (id === 'xuanyun') {
        topic = '眩晕'
    } else if (id === 'pifubing') {
        topic = '皮肤'
    }

    const firstTopic = await Document.find({ classify: topic, topic: 'firstTopic' }, { _id: 0, __v: 0 })
    const secondTopic = await Document.find({ classify: topic, topic: 'secondTopic' }, { _id: 0, __v: 0 })
    const thirdTopic = await Document.find({ classify: topic, topic: 'thirdTopic' }, { _id: 0, __v: 0 })
    const lastTopic = await Document.find({ classify: topic, topic: 'lastTopic' }, { _id: 0, __v: 0 })
    const topView = await top_view.findOne({ id }, { _id: 0, id: 0 })

    return new Promise(async (reslove, reject) => {
        Static_Data.findOne({ page: 'documentHome' }, { _id: 0 }).then(res => reslove({ documentHome: res, firstTopic, secondTopic, thirdTopic, lastTopic, topView })).catch(err => reject(err))
    })
}

//添加文档方法
function writeDocument(data) {
    return new Promise((reslove, reject) => {
        Document.findOne({ id: data.id }, { _id: 0 }).then(res => {
            console.log(res + '\t\n============')
            if (!res) {
                console.log('创建新的文档')
                Document.create(data, (err, res) => {
                    if (err) {
                        reject({ errMsg: err })
                    }
                    else {
                        console.log('添加成功!')
                        reslove({ errMsg: 'ok' })
                    }
                })
            } else {
                //修改方法
                console.log('修改id为' + res.id + '的文档')
                Document.updateOne({ id: data.id }, data).then(res1 => reslove(res1)).catch(err1 => reject(err1))
            }
        })
    })
}

//修改方法
function updateDocument(id, data) {

    return new Promise(async (reslove, reject) => {
        //创建连接
        await mongoose.connect(uri, options)


        const res = await Document.updateOne({ id }, data)
        reslove(res)
        mongoose.disconnect()
    })
}

//获取文档 
function getDocument(query) {
    console.log(query)
    return new Promise(async (reslove, reject) => {
        const totalNum = await Document.find({}).count()
        Document.find(query.condition, { _id: 0, __v: 0, image: 0 }, { limit: query.limit, skip: query.skip, sort: {id: -1} }).then(res => reslove({ res, totalNum })).catch(err => reject(err))
    })
}


function getNews(query) {
    return new Promise(async (reslove, reject) => {

        WeChat_Document.find(query.condition, { _id: 0, __v: 0 }, {
            limit: query.limit, skip: query.skip, sort: {id: -1}
        }).then(res => {
            reslove(res)
        }).catch(err => reject(err))
    })
}

module.exports = {
    getStaticData,
    writeDocument,
    getDocument,
    getTopicHome,
    updateDocument,
    writeYiriDoc,
    writeWeChatDoc,
    getNews
}